package com.itgacl.magic4j.modules.mp.handle;

import com.itgacl.magic4j.modules.mp.config.WxMpConfig;
import com.itgacl.magic4j.modules.mp.service.CoreService;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutTextMessage;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * 用户关注公众号Handler
 */
@Slf4j
@Component
public class SubscribeHandler extends AbstractHandler {

    @Autowired
    private CoreService coreService;

    @Autowired
    private WxMpConfig wxMpConfig;

    @Override
    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage, Map<String, Object> context,
                                    WxMpService wxMpService, WxSessionManager sessionManager) {
        WxMpUser wxMpUser = coreService.getUserInfo(wxMessage.getFromUser(), "zh_CN");
        log.info("SubscribeHandler 用户关注公众号，WxMpUser：{}",wxMpUser);

        //todo 处理用户关注公众号业务逻辑

        /**
         * 关注公众号后返回的提示语
         *
         * 尊敬的xxx，欢迎关注xxx！
         *
         * 点击下面链接进入公众号！
         * xxxxxxxx
         */
        String wxMpIndexUrl = "";
        String wxMpName = "";
        //跳转连接
        String linkUrl="https://open.weixin.qq.com/connect/oauth2/authorize?appid="+ wxMpConfig.getAppId()+"&redirect_uri="+wxMpIndexUrl+"&response_type=code&scope=snsapi_base&state=1#wechat_redirect";

        String indexUrl = "<a href=\""+linkUrl+"\">进入【公众号】>></a>";
        String content = "尊敬的【" + wxMpUser.getNickname() + "】，欢迎关注【"+wxMpName+"】！\n" +
                "点击下面链接进入公众号！\n" +
                indexUrl + "\n";

        WxMpXmlOutTextMessage m
            = WxMpXmlOutMessage.TEXT()
            .content(content)
            .fromUser(wxMessage.getToUser())
            .toUser(wxMessage.getFromUser())
            .build();
        logger.info("SubscribeHandler" + m.getContent());
        return m;
    }
}
